package models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.ManyToOne;

import org.joda.time.DateMidnight;
import org.joda.time.Interval;

import play.Logger;
import play.data.validation.Required;
import play.db.jpa.Model;

@Entity
public class Workday extends Model {

	@Required
	public Date startTime;

	@Required
	public Date endTime;

	@ManyToOne
	@Required
	public TimeUser owner;

	public TimeLocation location;

	public WorkdayType dayType;

	public Long totalWorkDuration;

	public Workday(Date start, Date end) {
		this.startTime = start;
		this.endTime = end;
	}

	public Workday() {
		dayType = WorkdayType.ABSENT;
		totalWorkDuration = 0L;
	}

	public static Workday getDefault(Date start) {
		Date startTime = TimeUtils.toMidnight(start);

		return new Workday(startTime, new Date(startTime.getTime()
				+ TimeUtils.getWorkHoursInMilis()));
	}

	public static boolean isValid(Workday workday) {
		return TimeUtils.daysBetween(workday.startTime, workday.endTime) == 0;
	}

	public static void validate(Workday workday) {
		// TODO Auto-generated method stub
	}

	public List<PunchTime> getTimePoints(TimeUser user) {
		List<PunchTime> timePoints = new ArrayList();

		PunchTime t1 = new PunchTime();
		t1.timeStamp = startTime;
		t1.user = user;

		PunchTime t2 = new PunchTime();
		t2.timeStamp = endTime;
		t2.user = user;

		timePoints.add(t1);
		timePoints.add(t2);

		return timePoints;
	}

	public static List<Workday> fetchWorkdays(Date from, Date to) {
		return new ArrayList<Workday>();
	}

	public static List<Workday> fetchWorkdaysForUser(TimeUser user) {
		// return all(Workday.class).filter("owner", user).fetch();
		return find("byOwner", user).fetch();
	}

	public static Workday findWorkdayforDay(Date when, TimeUser user) {
		DateMidnight todayBegins = new DateMidnight(new org.joda.time.DateTime(
				when));

		DateMidnight todayEnds = todayBegins.plusDays(1);

		Logger.info("Date time " + todayBegins.toDate().getTime() + " : "
				+ when.getTime() + " : " + todayEnds.toDate().getTime());

		JPAQuery query = Workday.find("byOwnerAndEndTimeBetween", user,
				todayEnds.toDate(), todayBegins.toDate());

		return query.first();
	}

	public Long getDuration() {
		if (startTime != null && endTime != null)
			return new Interval(startTime.getTime(), endTime.getTime())
					.toDurationMillis();
		else
			return 0L;
	}

	public enum WorkdayType {
		NORMAL, OVERWORK, SICK, HOLIDAY, ABSENT, FORGOT
	}
}
